﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Microsoft.SharePoint;
using System.Xml;
using System.ServiceModel.Syndication;

namespace CKS.Sandbox.TipOfTheDayProxy
{
    public class Proxy : Microsoft.SharePoint.UserCode.SPProxyOperation
    {
      
        public override object Execute(Microsoft.SharePoint.UserCode.SPProxyOperationArgs args)
        {
            string rssfeed = "";
            try
            {
                XmlReader reader = XmlReader.Create(((ProxyArgs)args).RssFeed.OriginalString);

                SyndicationFeed feed = SyndicationFeed.Load(reader);

                var RssItems = (from Item in feed.Items
                                select new
                                {
                                    Title = Item.Title.Text,
                                    Link = Item.Links[Item.Links.Count - 1].Uri.ToString(),
                                }).ToList();

                var element = RssItems.First();
                rssfeed = string.Format("\"{0}\",\"{1}\"", element.Title, element.Link);
            }
            catch
            {
                XDocument xfeed = XDocument.Load(((ProxyArgs)args).RssFeed.OriginalString);
                if (xfeed.Root.Name.LocalName == "rss")
                {

                    var RssItems = (from xElem in xfeed.Descendants("channel").Descendants("item")
                                    select new
                                    {
                                        Title = xElem.Descendants("title").FirstOrDefault().Value,
                                        link = xElem.Descendants("link").FirstOrDefault().Value,
                                    }).ToList();

                    var element = RssItems.First();
                    rssfeed = string.Format("\"{0}\"#~#\"{1}\"", element.Title, element.link);
                }
            }
        
            return rssfeed.ToString();
   
        }
    }
}
    